import Quill from 'quill';
import { WebsocketProvider } from 'y-websocket';
import * as Y from 'yjs';

const updateCursor = (quillCursors, aw, clientId, doc) => {
  try {
    if (aw && aw.cursor && clientId !== doc.clientID) {
      const user = aw.user || {};
      const color = user.color || '#fc4';
      const name = user.name || `User: ${clientId}`;
      quillCursors.createCursor(clientId.toString(), name, color);
      if (aw.cursor) {
        quillCursors.moveCursor(clientId.toString(), aw.cursor);
      }
    } else {
      quillCursors.removeCursor(clientId.toString())
    }
  } catch (error) {
    console.log(error);
  }
}

export class CollaborationService {
  constructor(wsUrl) {
    this.wsUrl = wsUrl;
  }

  updateAwareness (awareness, userId) {
    const user = {
      name: `User ${userId}`,
      color: `#${Math.floor(Math.random() * 0xffffff).toString(16)}`,
    };
    awareness.setLocalStateField('user', user);
  }

  setupCollaboration(docId, quill) {
    const ydoc = new Y.Doc();
    const provider = new WebsocketProvider(this.wsUrl, docId, ydoc);
    const ytext = ydoc.getText('quill');

    // new QuillBinding(ytext, quill, provider.awareness);

    // 初始化 Quill 内容
    quill.setContents(quill.clipboard.convert(ytext.toString()));
    this.bindYjsToQuill(ydoc, ytext, quill);

    // 自定义光标颜色
    this.updateAwareness(provider.awareness, ydoc.clientID);

    // 共享光标位置和状态信息
    this.setupCursors(provider, ytext, quill);

    provider.on('status', event => {
      console.log(event.status);
    });

    return { ydoc, provider };
  }

    // 监听 Quill 编辑器的变化并更新 Yjs 文档
    // 监听 Yjs 文档的变化并更新 Quill 编辑器
  bindYjsToQuill(ydoc, ytext, quill) {
    quill.on('text-change', (delta, oldDelta, source, origin) => {
      if (source === Quill.sources.USER) {
        ydoc.transact(() => {
          ytext.applyDelta(delta.ops);
        }, ytext);
      }
    });

    ytext.observe((event, transact) => {
      if (transact.origin!== ytext) {
        quill.updateContents(event.delta, 'yjs');
      }
    });
  }

  setupCursors(provider, ytext, quill) {
    const awareness = provider.awareness;
    const cursorsModule = quill.getModule('cursors');

     // 更新本地光标状态
     quill.on('selection-change', (range, oldRange, source) => {
      if (source === Quill.sources.USER) {
        if (range) {
          awareness.setLocalStateField('cursor', {
            index: range.index,
            length: range.length
          });
        } else {
          awareness.getLocalState() !== null &&
          awareness.setLocalStateField('cursor', null);
        }
      }
    });

    // 监听远程光标状态变化
    awareness.on('change', changes => {
      changes.added.forEach(clientId => {
        const state = awareness.getStates().get(clientId);
        updateCursor(cursorsModule, state, clientId, ytext.doc);
        // if (state && state.cursor) {
        //   cursorsModule.createCursor(clientId, `User ${clientId}`, 'blue');
        //   cursorsModule.moveCursor(clientId, state.cursor);
        // }
      });

      changes.updated.forEach(clientId => {
        const state = awareness.getStates().get(clientId);
        updateCursor(cursorsModule, state, clientId, ytext.doc);
        // if (state && state.cursor) {
        //   cursorsModule.createCursor(clientId, `User ${clientId}`, 'blue');
        //   cursorsModule.moveCursor(clientId, state.cursor);
        // }
      });

      changes.removed.forEach(clientId => {
        cursorsModule.removeCursor(clientId);
      });
    });
  }
}